import os

def deleteOtherWeightsFile(dir):
    files = os.listdir(dir)
    fileNames = []
    for file_name in files:
        if file_name.startswith("."):
            continue
        items = file_name.split('.')
        if len(items) != 4:
            continue
        fileNames.append((file_name, int(items[3])))

    fileNames = sorted(fileNames, key=lambda item: item[1], reverse=True)
    for file_name, _ in fileNames[1:]:
        f_path = os.path.join(dir, file_name)
        print 'delete file:', f_path
        os.remove(f_path)

def deleteFiles(filepath):
  files = os.listdir(filepath)
  for fi in files:
    fi_d = os.path.join(filepath, fi)
    if fi == 'weights':
        deleteOtherWeightsFile(fi_d)
    else:
        if os.path.isdir(fi_d):
            deleteFiles(fi_d)
        else:
          pass

if __name__ == "__main__":
    deleteFiles('./')